//
//  ToastView.m
//  LAEducation
//
//  Created by JiangXiaotao on 2014-10-29.
//  Copyright (c) 2014年 jxt. All rights reserved.
//

#import "ToastView.h"
#import "UIView+Util.h"

#define paddingX 18.f
#define paddingY 12.f
#define animateDuration .28f
#define maxWidth 200.f
#define indicatorSize CGSizeMake(30.f, 30.f)

@interface ToastView()

@property (nonatomic,retain) UIActivityIndicatorView *indicatorView;

@end

@implementation ToastView

- (id)initWithFrame:(CGRect)frame {
    
    if ((self = [super initWithFrame:frame])) {
        self.userInteractionEnabled = NO;
        self.alpha = 0;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
//        self.backgroundColor = [UIColor clearColor];
        self.backgroundColor = [UIColor colorWithWhite:.1f alpha:0.6f];
        self.layer.cornerRadius = 6.f;
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOffset = CGSizeMake(2, 2);
        self.layer.shadowRadius = 2.0f;
        self.layer.shadowOpacity = 0.2f;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
}

- (void)dealloc {
    [_textLabel release];
    [super dealloc];
}

#pragma mark - static method

+ (instancetype)showText:(NSString *)text interval:(NSTimeInterval)interval {
    ToastView *toast = [[ToastView alloc] init];
    toast.text = text;
    [toast showLoading:NO text:text interval:interval];
    return toast;
}

+ (instancetype)showLoading {
    ToastView *toast = [[ToastView alloc] init];
    [toast showLoading:YES text:nil interval:0];
    return toast;
}

+ (instancetype)showLoadingWithText:(NSString *)text {
    ToastView *toast = [[ToastView alloc] init];
    [toast showLoading:YES text:text interval:0];
    return toast;
}

+ (void)dismissAll {
    // iterate through all subviews of the window (top-level)
    for(UIView *view in [[[UIApplication sharedApplication] keyWindow] subviews]) {
        if([view isKindOfClass:[ToastView class]]) {
            [view removeFromSuperview];
        }
    }
}

#pragma mark - public method
- (void)show {
    [self showWithInterval:0];
}

- (void)showLoading:(BOOL)loading text:(NSString *)text interval:(NSTimeInterval)interval {
    [ToastView dismissAll];
    
    if(loading) {
        [self addSubview:self.indicatorView];
        [self.indicatorView startAnimating];
    }
    if (text) {
        [self addSubview:self.textLabel];
        self.text = text;
    }
    [self updateLayout];
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
    [UIView animateWithDuration:animateDuration animations:^{
        self.alpha = 1;
    }  completion:^(BOOL finished){
        if (interval > 0) {
            CGFloat seconds = interval / 1000;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                [self dismiss];
            });
        }
    }];

}

- (void)dismiss {
    [UIView animateWithDuration:animateDuration animations:^{
//        self.top -= 20.f;
        self.alpha = 0;
    }  completion:^(BOOL finished){
        if (self.indicatorView) {
            [self.indicatorView stopAnimating];
        }
        [self removeFromSuperview];
    }];
}

#pragma mark - setter Method

- (void)setText:(NSString *)text {
    self.textLabel.text = text;
}

- (void)updateLayout {
    if (self.textLabel.superview) {
        CGSize labelSize = [self.textLabel sizeThatFits:CGSizeMake(maxWidth, MAXFLOAT)];
        self.textLabel.height = labelSize.height;
        [self.textLabel sizeToFit];
        self.width = self.textLabel.width + paddingX * 2;
        self.height = self.textLabel.height + paddingY * 2;
    }
    if (self.indicatorView.superview) {
        self.indicatorView.centerX = round(self.width / 2);
        self.indicatorView.top = paddingY;
        self.textLabel.top = self.indicatorView.height + paddingY * 2;
        self.height += self.indicatorView.height + paddingY;
    }
    
//    CGRect windowFrame = [[UIApplication sharedApplication] keyWindow].frame;
//    NSUInteger yOffset = windowFrame.size.height - (self.frame.size.height / 2) - marginBottom;
    
    self.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 1.6);
    self.frame = CGRectMake(round(self.left), round(self.top), self.width, self.height);
}

#pragma mark - property Method

- (UIActivityIndicatorView *)indicatorView {
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        _indicatorView.frame = CGRectMake(indicatorSize.width / 2, indicatorSize.height / 2, indicatorSize.width, indicatorSize.height);
        _indicatorView.hidesWhenStopped = YES;
    }
    return _indicatorView;
}

- (UILabel *)textLabel {
    if (!_textLabel) {
        _textLabel = [[UILabel alloc] initWithFrame:CGRectMake(paddingX, paddingY, maxWidth, 0)];
        _textLabel.font = UIFontDefault;
        _textLabel.textColor = [UIColor whiteColor];
        _textLabel.backgroundColor = [UIColor clearColor];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        _textLabel.numberOfLines = 0;
        _textLabel.lineBreakMode = NSLineBreakByWordWrapping;
    }
    return _textLabel;
}
@end
